import cn from 'classnames';
import PropTypes from 'prop-types';
import React, { useState, useMemo } from 'react';
import InfoDisplay from './InfoDisplay';
import Table from './Table';
import ChartTitle from '../../../../components/ChartTitle';
import { datetime } from '../../../../../common/formatter';
import s from './style.module.css';

function getdate(type, isCurrent, httpCur, httpPrev, pingCur, pingPrev) {
	function getMaxTime(arr) {
		let max = 0;
		let id = -1;
		arr.forEach((item, idx) => {
			const today = new Date().getTime();
			const itemStamp = new Date(item).getTime();
			const stamp = today - itemStamp;
			if (stamp > max) {
				max = stamp;
				id = idx;
			}
		});
		return arr[id];
	}
	if (type === 'HTTP') {
		if (isCurrent) {
			return getMaxTime(httpCur);
		} else {
			return getMaxTime(httpPrev);
		}
	} else {
		if (isCurrent) {
			return getMaxTime(pingCur);
		} else {
			return getMaxTime(pingPrev);
		}
	}
}

function DetectDetail({
	className,
	task,
	prevTask,
	taskType,
	pingResult,
	httpResult,
	pingPrevResult,
	httpPrevResult,
}) {
	const [detectTime, setDetectTime] = useState('last');
	const taskList = detectTime === 'last' ? task : prevTask;
	const aviliableNode = JSON.parse(sessionStorage.aviliableNode) || null;

	const monitorTimes = useMemo(() => {
		return getdate(
			taskType.toUpperCase(),
			detectTime === 'last',
			httpResult.map(item => datetime(item.endTime)),
			httpPrevResult.map(item => datetime(item.endTime)),
			httpResult.map(item => datetime(item.endTime)),
			httpPrevResult.map(item => datetime(item.endTime))
		);
	}, [
		httpResult,
		pingResult,
		httpPrevResult,
		pingPrevResult,
		taskType,
		detectTime,
	]);
	const detailList = taskList?.result?.addition?.detail || [];

	const respInfo = {
		fast: detailList[0] || {},
		slowest: detailList[0] || {},
		avg: taskList?.result?.addition?.respAvg || 0,
	};
	const abnormalNodes = [];

	const pieData = { 异常: 0, 正常: 0 };

	const allNode = aviliableNode?.v4_area?.concat(aviliableNode?.v6_area).reduce((t, i) => {
		const item = JSON.parse(JSON.stringify(i));
		delete item.enable;
		t[Object.keys(item)[0]] = item[Object.keys(item)[0]];
		return t
	}, {})
	const settingsIPv4 = taskList?.taskSettings?.collect?.area?.map(i => { return { node: i, networkDisplayName: 'IPv4' } }) || []
	const settingsIPv6 = taskList?.taskSettings?.collect?.area_ipv6?.map(i => { return { node: i, networkDisplayName: 'IPv6' } }) || []
	const res = Object.values(detailList?.concat(settingsIPv4)?.concat(settingsIPv6)?.reduce((total, item) => {
		if (!total[`${item.node}_${item.networkDisplayName}`]) {
			if (!item.area) {
				item.area = allNode[item.node]
				item.securityStatus = 'error'
			}
			total[`${item.node}_${item.networkDisplayName}`] = item
		}
		return total
	}, {}) || {})
	res.forEach(item => {
		if (item.totalTime < respInfo.fast?.totalTime) {
			respInfo.fast = item;
		}
		if (item.totalTime > respInfo.slowest?.totalTime) {
			respInfo.slowest = item;
		}

		if (item.securityStatus === 'warning') {
			abnormalNodes.push(item.area);
			pieData['异常']++;
		} else if (item.securityStatus === 'safe') {
			pieData['正常']++;
		}
		return {
			node: item.area,
			statusCode: item.statusCode,
			respTime: item.totalTime,
			securityStatus: item.securityStatus,
		};
	});
	return (
		<div className={cn(className, s.detectDetail)}>
			<div className={s.head}>
				<ChartTitle className={s.title}>
					{taskType.toUpperCase()}监测详情
					<span className={s.date}>{monitorTimes}</span>
				</ChartTitle>
				<div className={s.btnContainer}>
					<div
						className={cn(s.speBtn, {
							[s.active]: detectTime === 'last',
						})}
						onClick={() => setDetectTime('last')}
					>
						当前监测
					</div>
					{!prevTask ? (
						<div className={s.disableBtn}>上一次监测</div>
					) : (
						<div
							className={cn(s.speBtn, {
								[s.active]: detectTime === 'prev',
							})}
							onClick={() => setDetectTime('prev')}
						>
							上一次监测
						</div>
					)}
				</div>
			</div>
			<div className={s.content}>
				<InfoDisplay
					key={Math.random().toString(36).slice(-6)}
					chartData={pieData}
					abnormalNodes={abnormalNodes}
					respInfo={respInfo}
				/>
				<Table key={Math.random().toString(36).slice(-6)} className='tableFormat' data={res} />
			</div>
		</div>
	);
}

DetectDetail.propTypes = {
	className: PropTypes.string,
	taskType: PropTypes.string,
	httpResult: PropTypes.array,
	httpPrevResult: PropTypes.array,
	pingResult: PropTypes.array,
	pingPrevResult: PropTypes.array,
	task: PropTypes.shape({
		result: PropTypes.shape({
			addition: PropTypes.shape({
				respAvg: PropTypes.number,
				detail: PropTypes.arrayOf(
					PropTypes.shape({
						respTime: PropTypes.number,
						node: PropTypes.string,
						securityStatus: PropTypes.string,
						statusCode: PropTypes.number,
					})
				),
			}),
		}),
	}),
	prevTask: PropTypes.shape({
		result: PropTypes.shape({
			addition: PropTypes.shape({
				respAvg: PropTypes.number,
				detail: PropTypes.arrayOf(
					PropTypes.shape({
						respTime: PropTypes.number,
						node: PropTypes.string,
						securityStatus: PropTypes.string,
						statusCode: PropTypes.number,
					})
				),
			}),
		}),
	}),
};
DetectDetail.defaultProps = {
	className: '',
};

export default DetectDetail;
